const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');

const adminAuth = require('./middlewares/admin-auth');
const userAuth = require('./middlewares/user-auth');

// 加载环境变量
require('dotenv').config();

const index = require('./routes/index');
const categories = require('./routes/categories');
const courses = require('./routes/courses');
const chapters = require('./routes/chapters');
const articles = require('./routes/articles');
const settings = require('./routes/settings');
const search = require('./routes/search');
const auth = require('./routes/auth');
const uses = require('./routes/users');
const likes = require('./routes/likes');
// const uploads = require('./routes/uploads');

const articlesRouter = require('./routes/admin/articles');
const categoriesRouter = require('./routes/admin/categories');
const settingsRouter = require('./routes/admin/settings');
const usersAdminRouter = require('./routes/admin/users');
const coursesRouter = require('./routes/admin/courses');
const chaptersRouter = require('./routes/admin/chapters');
const chartsRouter = require('./routes/admin/charts');
const authRouter = require('./routes/admin/auth');

const app = express();

app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 前台路由
app.use('/', index);
app.use('/categories', categories);
app.use('/courses', courses);
app.use('/chapters', chapters);
app.use('/articles', articles);
app.use('/settings', settings);
app.use('/search', search);
app.use('/auth', auth);
app.use('/users', userAuth, uses);
app.use('/likes', userAuth, likes);
// app.use('/uploads', userAuth, uploads);

// 后台路由, adminAuth: 鉴权中间件，通过后才能访问后台路由页面
app.use('/admin/articles', adminAuth, articlesRouter);
app.use('/admin/categories', adminAuth, categoriesRouter);
app.use('/admin/settings', adminAuth, settingsRouter);
app.use('/admin/users', adminAuth, usersAdminRouter);
app.use('/admin/courses', adminAuth, coursesRouter);
app.use('/admin/chapters', adminAuth, chaptersRouter);
app.use('/admin/charts', adminAuth, chartsRouter);
app.use('/admin/auth', authRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
